package com.davidk.survey.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.davidk.survey.server.constants.Constants;
import com.davidk.survey.server.user.User;


public class SessionInterceptor extends HandlerInterceptorAdapter {
	@SuppressWarnings("unused")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (true)
			return true;
		User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
		String uri = request.getRequestURI();
		String base = request.getContextPath();
		uri = uri.substring(base.length());
		if ((user == null && !uri.startsWith("/api/login")) || !user.isActive()) {
			request.getSession().invalidate();
			response.setContentType("application/json");
			response.getWriter().write("{\"error\":\"SESSION-EXPIRED\"}");
			return false;
		}
		return true;
	}

}
